package my.webservices.model;

import java.util.List;

import my.webservices.beans.VehHistSearchCriteria;
import my.webservices.beans.Vehicle;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * VehicleHistoryModel is the model for vehicle history service.
 * 
 * @author Nilaksh Bajpai.
 */
public class VehicleHistoryDataManagerImpl extends HibernateDaoSupport
		implements VehicleHistoryDataManager {

	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * @see my.webservices.model.VehicleHistoryDataManager#getVehiclesWithHistory(my.webservices.beans.VehHistSearchCriteria)
	 */
	public List<Vehicle> getVehiclesWithHistory(final VehHistSearchCriteria vhsCriteria) {
		logger.debug("vehicleCriteria :{}", vhsCriteria);

		Criteria criteria = getSession().createCriteria(Vehicle.class);
		criteria.createAlias("history", "history", Criteria.LEFT_JOIN);
		
		if (StringUtils.isNotBlank(vhsCriteria.getVin())) {
			criteria.add(Restrictions.eq("vin", vhsCriteria.getVin()));
		}
		if (StringUtils.isNotBlank(vhsCriteria.getVehicleNumber())) {
			criteria.add(Restrictions.eq("vehicleNumber", vhsCriteria.getVehicleNumber()));
		}
		if (StringUtils.isNotBlank(vhsCriteria.getModel())) {
			criteria.add(Restrictions.ilike("model", vhsCriteria.getModel(), MatchMode.START));
		}
		if (vhsCriteria.getMake() != null) {
			criteria.add(Restrictions.eq("make", vhsCriteria.getMake()));
		}
		
		criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
		
		criteria.addOrder(Order.asc("vehicleNumber"));
		
		List<Vehicle> vehicles = criteria.list();
		logger.debug("VehHist:{}", vehicles);

		return vehicles;
	}

	/**
	 * @see my.webservices.model.VehicleHistoryDataManager#save(my.webservices.beans.Vehicle)
	 */
	public void save(Vehicle veh) {
		logger.debug("Before save, veh:{}", veh);
		getSession().saveOrUpdate(veh);
		logger.debug("After save, vehHist:{}", veh);
	}

}
